package cn.patpang.config;

import cn.patpang.core.vo.HttpResponseError;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @Title ValidateControllerAdvice.java
 * @Author PangPX
 * @Data 2017年6月21日 下午3:53:28
 */
@ControllerAdvice
public class ControllerExceptionHandlerAdvice {

    /**
     * 参数错误
     *
     * @param bindException
     * @param response
     */
    @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    public void paramsError(Exception bindException, HttpServletResponse response) {
        List<FieldError> fieldErrors;
        HashMap<String, String> attrMap;
        String errMsg;


        if (bindException.getClass().equals(MethodArgumentNotValidException.class)) {
            fieldErrors = ((MethodArgumentNotValidException) bindException).getBindingResult().getFieldErrors();
        } else {
            fieldErrors = ((BindException) bindException).getBindingResult().getFieldErrors();
        }

        attrMap = new HashMap<String, String>();
        for (FieldError error : fieldErrors) {
            errMsg = error.getDefaultMessage();
            if (StringUtils.isNotBlank(errMsg = errMsg.trim())) {
                if (errMsg.startsWith("{") && errMsg.endsWith("}")) {
                    errMsg = errMsg.substring(1, errMsg.length() - 1);
                }
                errMsg = HttpResultMessage.get("httpresult.400000." + errMsg);
            }

            attrMap.put(error.getField(), errMsg);
        }

        this.writerResult(response, new HttpResponseError(400, "error params", attrMap));
    }

    /**
     * 输出json
     *
     * @param response
     * @param errorResponseView
     */
    private void writerResult(HttpServletResponse response, HttpResponseError errorResponseView) {
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(errorResponseView.getErrCode());
            response.getWriter().write(JSON.toJSONString(errorResponseView));
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
